//创建用户相关的小仓库
import { defineStore } from "pinia";
import { UserState } from './type';
import { getUserInfo, deleteInfoCode, loginApi } from "../../api/login";
import { sessionStorage } from '../../utils/storage';

const userStore = defineStore('user', {
  state: (): UserState => {
    return {
      // token: 'zijixiedetoken',
      token: sessionStorage.get('token') || '',
      isAdmin: '',
      username: '',
      sysInfo: {}
    }
  },
  actions: {
    // 登录
    userLogin(data: { username: string, password: string }, callback: () => void) {
      return new Promise((resolve, reject) => {
        loginApi(data).then(async (res) => {
          resolve('')
          if (res.data && res.data) {
            this.token = res.data
            sessionStorage.set('token', this.token)
            // await this.getInfo()
            callback()
          }
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 获取用户基本信息
    async getInfo() {
      const infoData = await getUserInfo()
      this.username = infoData.data.user.nickName
      this.isAdmin = infoData.data.roles[0]
      this.sysInfo = infoData.data.user
      sessionStorage.set('rowInfo', {
        username: infoData.data.user.nickName,
        isAdmin: infoData.data.roles[0],
        sysInfo: infoData.data.user
      })
    },
    //退出登录
    resetToken() {
      return new Promise((resolve) => {
        deleteInfoCode().then(() => {
          sessionStorage.remove('token');
          sessionStorage.remove('rowInfo');
          // this.RESET_STATE();
          resolve(null);
        })
      });
    },
  },
  getters: {

  }
})
//d对外暴漏
export default userStore;

